package com.longxi.tianjintianbao;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.multidex.MultiDex;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataUserController;
import com.longxi.tianjintianbao.greedao.dao.DaoMaster;
import com.longxi.tianjintianbao.greedao.dao.DaoSession;
import com.longxi.tianjintianbao.greedao.entity.User;
import com.longxi.tianjintianbao.model.PropertyCompany;
import com.longxi.tianjintianbao.utils.GlobalUtils;
import com.squareup.leakcanary.LeakCanary;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

public class MyApplication extends Application {
    private DaoMaster.DevOpenHelper mHelper;
    public static SQLiteDatabase db;
//    public static Database db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private static Map<String, MySubscriber> mySubscriberMap;
    private RequestOptions options;
    private RequestOptions options2;

    //静态单例
    public static MyApplication instances;

    public static User loginUser = null;//临时放置用户登录后的信息
    //zp联调专用
//    public static String IP = "http://60.28.230.156:9706/tjtbzcApp/api/Interface/";//选择后的ip地址
    public static String IP = "http://122.112.207.114:9126/tjtbzcApp/api/Interface/";//远程地址旧
//    public static String IP = "http://192.168.1.66:801/api/Interface/";//选择后的ip地址


//    public static String IP = "http://221.239.19.222:802/api/Interface/";//自己得后台新
    public static String IPID = "3";//选择后的ipid
    public static String COMPANY = "天津天保";//选择IP后的企业名
    public static List<PropertyCompany> propertyCompanieList;//放物业IP
    public static Map<String, PropertyCompany> propertyCompanieList2;//放物业IP
    public static String username = "";//盘点登录账号密码
    public static String password = "";
    public static boolean isPDLogin = false;

    @Override
    public void onCreate() {
        super.onCreate();
        instances = this;
        _initConfig();
        _initRequestOptions();
        _setDatabase();
        getLoginUser();
        if("debug".equals(BuildConfig.ENVIRONMENT)){
            _leakCanary();
        }
    }

    //获取已登录用户
    private void getLoginUser(){
        loginUser = DataUserController.findByIslogin("1");
    }

    private void _leakCanary() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return;
        }
        LeakCanary.install(this);
    }

    public static MyApplication getInstance(){
        return instances;
    }

    /**
     * 设置greenDao
     */
    private void _setDatabase() {
    // 通过 DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为 greenDAO 已经帮你做了。
        // 注意：默认的 DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。
        // 所以，在正式的项目中，你还应该做一层封装，来实现数据库的安全升级。
        mHelper = new DaoMaster.DevOpenHelper(this, "tjtb-db", null);
        db = mHelper.getWritableDatabase();
//        db = mHelper.getEncryptedWritableDb("123");
        // 注意：该数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }
    public DaoSession getDaoSession() {
        return mDaoSession;
    }
    public SQLiteDatabase getDb() {
        return db;
    }
//    public Database getDb() {
//        return db;
//    }

    /**
     * 初始化配置
     */
    private void _initConfig() {
        GlobalUtils.init();
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);

        String RegistrationID = JPushInterface.getRegistrationID(MyApplication.getInstance());
        if(!"".equals(RegistrationID)){
            AppConst.identification = RegistrationID;
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 网络请求时需要将MySubscriber存放到map中方便管理
     * @param key
     * @param s
     */
    public static void saveSubscriber(String key,MySubscriber s) {
        if (mySubscriberMap == null) {
            mySubscriberMap = new HashMap<>();
        }
        mySubscriberMap.put(key,s);
    }

    /**
     * activity销毁时需要将MySubscriber销毁 避免空指针异常
     * @param key
     */
    public static void unSubscribe(String key) {
        if (mySubscriberMap != null) {
            MySubscriber subscription = mySubscriberMap.get(key);
            if(subscription != null){
                subscription.unsubscribe();
                mySubscriberMap.remove(key);
            }
        }
    }

    /**
     * glide配置
     */
    private void _initRequestOptions() {
        options = new RequestOptions()
                .centerCrop()
                .placeholder(R.mipmap.ic_load_image)
                .error(R.mipmap.ic_error_image);

        options2 = new RequestOptions()
                .centerCrop()
                .placeholder(R.color.gainsboro2)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
    }

    public RequestOptions getOptions(){
        return options;
    }

    public RequestOptions getPicSelectOptions(){
        return options2;
    }
}
